package com.gxb.codebook;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.widget.Toast;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import androidx.activity.EdgeToEdge;

import com.gxb.codebook.database.SQLiteHelper;

public class MainActivity extends AppCompatActivity {

    private TextView textViewTimer;
    private CountDownTimer countDownTimer;
    private SQLiteHelper dbHelper;
    private BroadcastReceiver themeChangeReceiver;
    private LocalBroadcastManager localBroadcastManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        textViewTimer = findViewById(R.id.textView);

        // 初始化LocalBroadcastManager
        localBroadcastManager = LocalBroadcastManager.getInstance(this);

        // 初始化内部文件目录
        File appFilesDir = getFilesDir();
        File appExternalFilesDir = getExternalFilesDir(null);
        if (!appFilesDir.exists()) {
            appFilesDir.mkdirs();
        }
        if (appExternalFilesDir != null && !appExternalFilesDir.exists()) {
            appExternalFilesDir.mkdirs();
        }

        dbHelper = new SQLiteHelper(this);
        dbHelper.getWritableDatabase();
        mkdir();
        readTheme();
        initBroadcastReceiver();
        onFinish();
    }

    private void initBroadcastReceiver() {
        themeChangeReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if ("THEME_CHANGED".equals(intent.getAction())) {
                    recreate();
                }
            }
        };

        IntentFilter filter = new IntentFilter("THEME_CHANGED");
        localBroadcastManager.registerReceiver(themeChangeReceiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        if (localBroadcastManager != null && themeChangeReceiver != null) {
            try {
                localBroadcastManager.unregisterReceiver(themeChangeReceiver);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
    }

    private void readTheme() {
        File internalFile = new File(getFilesDir(), "theme.txt");
        try {
            if (internalFile.exists()) {
                byte[] bytes = new byte[(int) internalFile.length()];
                FileInputStream fis = new FileInputStream(internalFile);
                fis.read(bytes);
                fis.close();
                String theme = new String(bytes);

                if ("dark".equals(theme)) {
                    drakThere();
                } else {
                    sunThere();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            sunThere(); // 发生错误时使用默认主题
        }
    }

    private void sunThere() {
        // 1. 设置应用主题为浅色
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);

        // 2. 更新主题文件
        try {
            File themeFile = new File(getFilesDir(), "theme.txt");
            FileOutputStream fos = new FileOutputStream(themeFile);
            fos.write("sun".getBytes());
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 3. 向所有Activity广播主题变更
        Intent intent = new Intent("THEME_CHANGED");
        intent.putExtra("theme", "sun");
        localBroadcastManager.sendBroadcast(intent);

        // 4. 发送主题切换为浅色的广播
        Intent sunIntent = new Intent("THEME_SET_TO_SUN");
        localBroadcastManager.sendBroadcast(sunIntent);
    }

    private void drakThere() {
        // 1. 设置应用主题为深色
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);

        // 2. 更新主题文件
        try {
            File themeFile = new File(getFilesDir(), "theme.txt");
            FileOutputStream fos = new FileOutputStream(themeFile);
            fos.write("dark".getBytes());
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 3. 向所有Activity广播主题变更
        Intent intent = new Intent("THEME_CHANGED");
        intent.putExtra("theme", "dark");
        localBroadcastManager.sendBroadcast(intent);

        // 4. 发送主题切换为深色的广播
        Intent darkIntent = new Intent("THEME_SET_TO_DARK");
        localBroadcastManager.sendBroadcast(darkIntent);
    }

    public void onFinish() {
        // 发送应用启动完成的广播
        Intent startIntent = new Intent("APP_STARTUP_COMPLETE");
        localBroadcastManager.sendBroadcast(startIntent);

        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    protected void mkdir() {
        File internalFile = new File(getFilesDir(), "theme.txt");
        try {
            if (!internalFile.exists()) {
                internalFile.createNewFile();
                // 写入默认主题
                FileOutputStream fos = new FileOutputStream(internalFile);
                fos.write("sun".getBytes());  // 默认使用浅色主题
                fos.close();

                // 发送主题文件创建的广播
                Intent createIntent = new Intent("THEME_FILE_CREATED");
                createIntent.putExtra("default_theme", "sun");
                localBroadcastManager.sendBroadcast(createIntent);
            }
        } catch (Exception e) {
            e.printStackTrace();

            // 发送主题文件创建失败的广播
            Intent failIntent = new Intent("THEME_FILE_CREATE_FAILED");
            localBroadcastManager.sendBroadcast(failIntent);
        }
    }
}
